package run.halo.app.service.front.impl;

import java.util.Optional;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import run.halo.app.model.entity.front.Customer;
import run.halo.app.model.support.FrontConstant;
import run.halo.app.model.vo.front.CustomerVO;
import run.halo.app.repository.front.CustomerRepository;
import run.halo.app.service.base.AbstractCrudService;
import run.halo.app.service.front.CustomerService;

@Service
public class CustomerServiceImpl extends AbstractCrudService<Customer,Integer> implements
    CustomerService {

    private final CustomerRepository customerRepository;
    private final StringRedisTemplate redisTemplate;

    public CustomerServiceImpl(CustomerRepository customerRepository,
        StringRedisTemplate redisTemplate) {
        super(customerRepository);
        this.customerRepository = customerRepository;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Optional<Customer> findByUsername(String username) {
        return customerRepository.findByUsername(username);
    }

    @Override
    public Optional<Customer> findByEmail(String email) {
        return customerRepository.findByEmail(email);
    }

    @Override
    public Optional<Customer> findByPhoneNumber(String phoneNumber) {
        return customerRepository.findByPhoneNumber(phoneNumber);
    }

    @Override
    public Optional<Customer> findByUuid(String UUID) {
        return customerRepository.findByUuid(UUID);
    }

    @Override
    public Optional<CustomerVO> findByToken(String token) {
        String s = redisTemplate.opsForValue().get(FrontConstant.REDIS_CUSTOMER_AUTH_TOKEN + token);
        if(ObjectUtil.isNotEmpty(s)){
            Customer customer = JSONObject.parseObject(s, Customer.class);
            CustomerVO vo = new CustomerVO();
            BeanUtil.copyProperties(customer,vo);
            vo.setEmail(DesensitizedUtil.email(vo.getEmail()));
            vo.setPhoneNumber(DesensitizedUtil.mobilePhone(vo.getPhoneNumber()));
            return Optional.of(vo);
        }
        return Optional.empty();
    }
}
